<?php
namespace App\Libs\Common;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Libs\Vendor\AliPaySdk\aop\request\ZhimaMerchantOrderRentModifyRequest;
use App\Libs\Vendor\AliPaySdk\aop\request\ZhimaMerchantOrderRentCreateRequest;
use App\Libs\Vendor\AliPaySdk\aop\request\ZhimaMerchantOrderRentQueryRequest;
use App\Libs\Vendor\AliPaySdk\aop\request\ZhimaMerchantOrderRentCompleteRequest;

use App\Libs\Vendor\AliPaySdk\aop\request\ZhimaMerchantOrderRentCancelRequest;
use App\Libs\Vendor\AliPaySdk\aop\request\ZhimaMerchantBorrowEntityUploadRequest;

use App\Libs\Vendor\AliPaySdk\aop\request\AlipayTradeWapPayRequest;
use App\Libs\Vendor\AliPaySdk\aop\request\AlipayTradeQueryRequest;













use App\Libs\Vendor\AliPaySdk\aop\AopClient;


/*H5 信用借还(蚂蚁金服)*/
class ZmXyController extends Controller
{	
	
		private $aop=null;
	    
	    private $appId='2017081408189483';
        private $gatewayUrl='https://openapi.alipay.com/gateway.do';	
        /*商户私钥*/	
        private $rsaPrivateKey='MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCdm3kB67QWWcU7418m+CEBPA5KGnppiLAz97s7MKI/modc4Y6jC98ickvXv4h7JbW0+sorIZq29w0miteKFGReeyROwXTrNaaWVRlRVxR+qWDTOsJgihpOPX/lkDFud0EFjTMRyK9/60/C+uDI1HIXLDxzDZBmz+zHbXtWVPGc/KZeGa/CAA6aTSQygT9OrS2BlUCsBXZuCY8bhmxXWtrgSGOQsjg6oz3h4xy5QiYhLJnbPKVBuZrd4T/SPGq69AkvNUQOvSsoGvpQmTm7+Lkmw7ADHn445joLG3gmzd0a942h4IYxM7jdc2QxzIzRQ8YW5MpQXXieoA7j+RQxCqCnAgMBAAECggEALA38WiQXd7PqJN5eh5cOKrktyVrzYrJ5hl018cqbX6oDMlw+Macs3QUT3B/Gt52H2CnN/xZ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G4n7Arev7HyOGYK/+ajAMUBfRZMIEqSaC69vMZBx+CosYPgSCny57KOTNEoE4c58u2M5wgrVJ8Q==';

        /**商户公钥**/
        private $rsaPublicKey  = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnZt5Aeu0FlnFO+NfJvghATwOShp6aYiwM/e7OzCiP5qHXOGOowvfInJL17+IeyW1tPrKKyGatvcNJorXihRkXnskTsF06zWmllUZUVcUfqlg0zrCYIoaTj1/5ZAxbndBBY0zEcivf+tPwvrgyNRyFyw8cw2QZs/sx217VlTxnPymXhmvwgAOmk0kMoE/Tq0tgZVArAV2bgmPG4ZsV1ra4EhjkLI4OqM94eMcuUImISyZ2zylQbma3eE/0jxquvQJLzVEDr0rKBr6UJk5u/i5JsOwAx5+OOY6Cxt4Js3dGveNoeCGMTO43XNkMcyM0UPGFuTKUF14nqAO4/kUMQqgpwIDAQAB";

        /*支付宝公钥*/		
        private $alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoOXnC0KCo9UaC+6+aE7JivhXw5Rzcmi5o5yoKg663hWJX4CRXYmoWhP3NyIQStrUxABlcm+UMEeCQYPqbF7c0C5YYS3vF/20TS0Sa2EOBzJvp+bbw4JvZdZHxS6seMoAN2/HOrsOoPlQEvqC95wwmzGNkhm6dCvJKJtc6/bXc77aH2kY+T+0QP6O6t+zJX189xRDoRU6fs+g9rPsN0gLwiXKbe45ncXrMhWE4iVWvRHd9badh2P9f4vyCqre5yYO1Dep3RlgRs1Sil0799lSMLgCSB2NP/Nw+xZdiFDqXL8bDT55NkSMvGSfbFYG48JNl3K7isN4eEDz3YPe/4k5mQIDAQAB';		

		public function _initialize()
		{   
			header("Content-type: text/html; charset=utf-8");
			if (is_null($this->aop))
			{
				$this->aop= new AopClient();
			}

			$this->aop->appId = $this->appId;
			$this->aop->gatewayUrl = $this->gatewayUrl;
			$this->aop->rsaPrivateKey = $this->rsaPrivateKey;
			$this->aop->alipayrsaPublicKey=$this->alipayrsaPublicKey;
		}
		



		/*
	     *  信用借还订单创建(页面)
		*/
		public function orderRentCreate($arr)
		{	
				$tmp = stripos($arr['goods_name'],'&');

				if ($tmp!==false) 
				{
					$arr['goods_name']=str_replace("&"," ",$arr['goods_name']);
				}
			
				$request = new  ZhimaMerchantOrderRentCreateRequest();
				$request->setBizContent("{" .
				"\"invoke_type\":\"WINDOWS\"," .
				"\"invoke_return_url\":\"".$arr['invoke_return_url']."\"," .
				"\"invoke_state\":\"{\\\\\\\"xxx\\\\\\\":\\\\\\\"xxx\\\\\\\"}\"," .
				"\"out_order_no\":\"".$arr['out_order_no']."\"," .
				"\"product_code\":\"w1010100000000002858\"," .
				"\"goods_name\":\"".$arr['goods_name']."\"," .
				"\"rent_info\":\"".$arr['rent_info']."\"," .
				"\"rent_unit\":\"".$arr['rent_unit']."\"," .
				"\"rent_amount\":\"".$arr['rent_amount']."\"," .
				"\"deposit_amount\":\"".$arr['deposit_amount']."\"," .
				"\"deposit_state\":\"Y\"," .
				"\"borrow_shop_name\":\"绿悦出品\"," .
				"\"name\":\"".$arr['name']."\"," .
				"\"cert_no\":\"".$arr['cert_no']."\"," .
				"\"rent_settle_type\":\"alipay\"," .
				"\"borrow_time\":\"".$arr['borrow_time']."\"," .
				"\"expiry_time\":\"".$arr['expiry_time']."\"," .
				"\"mobile_no\":\"".$arr['mobile_no']."\"," .
				"\"address\":\"".$arr['address']."\"," .
				"  }");

				$result = $this->aop->pageExecute ($request); 

				print_r($result);
				
				echo $result;
		}

		/**
		 * 创建信用借还页面后异步通知地址
		 */
         public function orderRentCreate_notify()
         {	
	         	/*验证签名*/
	         	$request=request()->all();
	 			
	       	  	// 验证网关请求
				if ($request["service"] == "alipay.service.check") 
				{
					$this->verifygw(true,$request);
				}

	         	$order_no=$request['order_no'];
	         	$out_order_no=$request['out_order_no'];

	         	$checkSign=$this->aop->rsaCheckV2($request,$this->alipayrsaPublicKey,$request['sign_type']);

	         	if ($checkSign) 
	         	{	
	         		$log['notify_type']=$request['notify_type'];
					$log['out_order_no']=$request['out_order_no'];
					$log['zm_order_no']=$request['order_no'];
					$log['log']=json_encode($request);
					$log['create_time']=date("Y-m-d H:i:s");

	         		//1.查询订单状态
	         		$row=DB::table('orders')->where("order_id",$out_order_no)->field("user_phone","user_name","goods_name","order_tenancy_term","order_status")->get();
	         		$row=ob_to_array($row);

	         		//订单创建异步事件
		         	if ('ORDER_CREATE_NOTIFY' == $request['notify_type']) 
		         	{
		         		if ($row['order_status']==0) 
		         		{
		         			$saveOrder=DB::table('orders')->where("order_id",$out_order_no)->update(array('order_status'=>1,'zm_order_no'=>$order_no));

		         			if ($saveOrder) 
		         			{
		         				$log['keyword']='订单创建成功';

		         				orderSucSmsCode($row['user_phone'],$row['goods_name'],$row['user_name'],$row['order_tenancy_term']);
		         			}
		         		}
		         	}

		         	//订单完结异步事件
		         	if ('ORDER_COMPLETE_NOTIFY'== $request['notify_type']) 
		         	{
		         			$log['keyword']='订单已完结';

		         			$saveOrder=DB::table('orders')->where("zm_order_no",$order_no)->update(array('order_status'=>5));
		         	}

		         	DB::table('log_xyjh')->insert($log);

		         	echo "success";  //成功

	         	}else{

	         		//file_put_contents(time().'.txt','信用借还验签失败'.json_encode($request));

	         		echo "fail";   //失败
	         	}
         
         }

      public function verifygw($is_sign_success,$request) 
      {

		  $biz_content=mb_convert_encoding($request["biz_content"],'utf-8','GBK');


		  $xml = simplexml_load_string ($biz_content);


		  $EventType = ( string ) $xml->EventType;

		//if ($EventType == "verifygw") 
		//{

			$charset='GBK';
			$sign_type='RSA2';

			if ($is_sign_success) {
				$response_xml = "<success>true</success><biz_content>" . $this->rsaPublicKey. "</biz_content>";

			} else { 
				$response_xml = "<success>false</success><error_code>VERIFY_FAILED</error_code><biz_content>" .$this->rsaPublicKey . "</biz_content>";
			}
			
			$mysign=$this->aop->alonersaSign($response_xml,$this->rsaPrivateKey,$sign_type);
			$return_xml = "<?xml version=\"1.0\" encoding=\"".$charset."\"?><alipay><response>".$response_xml."</response><sign>".$mysign."</sign><sign_type>".$sign_type."</sign_type></alipay>";

			echo $return_xml;
			exit ();
		//}
	   }
		

		/**
		 *  信用借还查询
		 *  cancel  取消
		 */
		public function orderRentQuery()
		{	
			$out_order_no='180111162128665';

			$request = new  ZhimaMerchantOrderRentQueryRequest ();
			$request->setBizContent("{" .
			"\"out_order_no\":\"".$out_order_no."\"," .
			"\"product_code\":\"w1010100000000002858\"" .
			"  }");
			$result = $this->aop->execute ( $request); 

			print_r($result);
			return $result['zhima_merchant_order_rent_query_response'];
		}

        
       
		public function test()
		{
			$res=$this->orderRentComplete('96095092');

			var_dump($res);
		}


		/**
		 *  信用借还订单完结
		 */
		
		public function orderRentComplete($order_no,$pay_amount=0)
		{	
			/*信用借还订单号*/
			$restore_time=date('Y-m-d H:i:s');  //完结时间
			$request = new ZhimaMerchantOrderRentCompleteRequest();
			$request->setBizContent("{" .
			"\"order_no\":\"".$order_no."\"," .
			"\"product_code\":\"w1010100000000002858\"," .
			"\"restore_time\":\"".$restore_time."\"," .
			"\"pay_amount_type\":\"RENT\"," .
			"\"pay_amount\":\"".$pay_amount."\"," .
			"\"restore_shop_name\":\"绿悦出品\"," .
			"  }");
			$result =$this->aop->execute($request); 

			echo "<pre>";
			print_r($result);
			echo "</pre>";
			if($result['zhima_merchant_order_rent_complete_response']['code'] == '10000')
			{
				return true;
			}else{
				return false;
			}
		}
  	
		/**
		 *  信用借还订单撤销(取消)
		 *  @param  order_no  信用借还内部单号
		 */
		
		public function orderRentCancel($order_no)
		{	

			$request = new ZhimaMerchantOrderRentCancelRequest ();
			$request->setBizContent("{" .
			"\"order_no\":\"".$order_no."\"," .
			"\"product_code\":\"w1010100000000002858\"" .
			"  }");
			
			$result = $this->aop->execute ($request); 

			return $result;

			if ($result['zhima_merchant_order_rent_cancel_response']['code'] =='10000') 
			{
				return true;
			}else{
				return false;
			}
	   }


	   /**
	    *  信用借还借用实体数据上传接口 初次使用时调用(仅使用一次)
	    */
	
	   public function borrowEntityUpload()
	   {		
				$request = new ZhimaMerchantBorrowEntityUploadRequest ();
				$request->setBizContent("{" .
				"\"product_code\":\"w1010100000000002858\"," .
				"\"category_code\":\"umbrella\"," .
				"\"entity_code\":\"2016000100010011\"," .
				"\"longitude\":\"83.66\"," .
				"\"latitude\":\"5.87\"," .
				"\"entity_name\":\"爱心雨伞\"," .
				"\"address_desc\":\"杭州市西湖区文三路478号\"," .
				"\"office_hours_desc\":\"09:00—22:00\"," .
				"\"contact_number\":\"0571-26888888\"," .
				"\"collect_rent\":\"Y\"," .
				"\"rent_desc\":\"5元/小时\"," .
				"\"can_borrow\":\"Y\"," .
				"\"can_borrow_cnt\":\"12\"," .
				"\"total_borrow_cnt\":\"20\"," .
				"\"upload_time\":\"2017-01-01 15:34:38\"" .
				"  }");
				$result = $this->aop->execute ( $request); 

				$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
				$resultCode = $result->$responseNode->code;
				if(!empty($resultCode)&&$resultCode == 10000){
				echo "成功";
				} else {
				echo "失败";
				}
	   }

	   /**
	    *  信用借还订单修改接口
	    *  @param order_no     信用借还内部订单号
	    *  @param borrow_time  开始时间(发货时间加5天)      格式：Y-m-d H:i:s
	    *  @param expiry_time  发货时间加5天后加上分期月份   格式：Y-m-d H:i:s
	    */
      public function orderRentModify($order_no,$borrow_time,$expiry_time)
      {		
      	 	$request = new  ZhimaMerchantOrderRentModifyRequest();
			$request->setBizContent("{" .
			"\"order_no\":\"".$order_no."\"," .
			"\"product_code\":\"w1010100000000002858\"," .
			"\"borrow_time\":\"".$borrow_time."\"," .
			"\"expiry_time\":\"".$expiry_time."\"" .
			"  }");

			$result = $this->aop->execute ($request); 	

			if ($result['zhima_merchant_order_rent_modify_response']['code'] == '10000') 
			{
				return true;
			}else{
				return false;
			}
      }


      /**
       * 支付
       * @param  out_trade_no    订单号(账单分期表ID)
       * @param  subject         商品名称
       * @param  total_amount    金额
       */
      public function alipay($out_trade_no,$subject,$total_amount)
      {
	        $notify_url = "https://n.lvyuecp.com/index.php/OutApi/ZmXy/alipay_notify";
	        //同步跳转
	        $return_url= "https://n.lvyuecp.com/index.php/OutApi/ZmXy/alipay_return";

	  	    //订单名称，必填
		    $biz_content['subject'] =$subject;
		     //商品描述，可空
		    $biz_content['body'] ='';

		    //商户订单号，商户网站订单系统中唯一订单号，必填
		    $biz_content['out_trade_no'] = $out_trade_no;

		    //付款金额，必填
		    $biz_content['total_amount'] =$total_amount;

		    //超时时间
		    $biz_content['timeout_express'] = "30m";

	      	$request = new  AlipayTradeWapPayRequest();

	      	$request->setNotifyUrl($notify_url);
	        $request->setReturnUrl($return_url);
	        $request->setBizContent (json_encode($biz_content));
	    	
		    $result = $this->aop->pageExecute($request);

		    echo  $result;
      }

      /*
       *   查询支付结果
	   *  @param 	out_trade_no    绿悦订单号
	   *  @param 	trade_no        支付单号  //$out_trade_no="HB2018090312005656509850",$trade_no='2018090322001473631001515957'
      */
      private function query($out_trade_no,$trade_no)
      {
      	 	//订单名称，必填
		    $biz_content['outTradeNo']=$out_trade_no;

		     //商品描述，可空
		    $biz_content['trade_no'] =$trade_no;

	      	$request = new AlipayTradeQueryRequest();

	        $request->setBizContent (json_encode($biz_content));
	    	
		    $result = $this->aop->execute($request);

			return $result['alipay_trade_query_response'];
      }


      /**
       * 支付异步通知
       * @return [type] [description]
       */
      public function alipay_notify()
      {		
      	   header("Content-type: text/html; charset=utf-8");

	      	$request=I();

	      	if (!$request) exit("no");

	      	$res_rsaCheck=$this->aop->rsaCheckV1($request,$this->alipayrsaPublicKey,$request['sign_type']);

	      	//分期表ID
	      	$out_trade_no=$request['out_trade_no'];
	      	//交易状态
	      	$trade_status=$request['trade_status'];

	      	$total_amount=$request['total_amount'];

	      	$log['order_stages_id']=$out_trade_no;
	      	$log['trade_status']=$trade_status;
	      	$log['log']=json_encode($request);
	      	$log['create_time']=date("Y-m-d H:i:s");

	      	if (!$res_rsaCheck) 
	      	{
	      	   $log['keyword']='验签失败 ';	
	      	}

	      	//交易关闭
	      	if ($trade_status == 'TRADE_CLOSED') 
	      	{
	      		$order_stages_id_new=build_order_no();

	      		//全款支付
	      		$count=DB::table("orders")->where([['zm_order_no',$out_trade_no],['order_type',2]])->count();

	      		if($count)
	      		{
	      			$res=DB::table('orders')->where([['zm_order_no',$out_trade_no],['order_type',2]])->update(array('zm_order_no'=>"HB".$order_stages_id_new));
	      		}else{
	      			//分期付款
			    	$res=DB::table('order_stages')->where("id",$out_trade_no)->update(array('id'=>$order_stages_id_new,'remarks'=>"交易关闭,原订单号:$out_trade_no"));
	      		}	

	      		if ($res) 
		    	{
		    		$log['keyword'].='交易关闭,新订单:'.$order_stages_id_new;
		    		echo "success";
		    	}else{
		    		$log['keyword'].='交易关闭信息更改失败';
		    		echo "fail";
		    	}
	      	}


	      	/*
	      		交易成功,支持退款
	      	 */
		    if($trade_status == 'TRADE_SUCCESS') 
		    {	
		    	$log['keyword'].='支付成功';

				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				//请务必判断请求时的total_amount与通知时获取的total_fee为一致的
				//如果有做过处理，不执行商户的业务程序
						
				//注意：
				//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知

		       //全款支付
	      	   $count=DB::table("orders")->where([['zm_order_no',$out_trade_no],['order_type',2]])->count();
	      	   if($count)
	      	   {   
	      	   	   $res=DB::table("orders")->where([['zm_order_no',$out_trade_no],['order_type',2]])->update(array("order_status"=>2,'order_rema_amount_pay'=>0,'order_repay_period'=>0,'order_amount_actually_paid'=>$total_amount));
	      	   }else{
	      	   	   $res=save_order_stages($out_trade_no,$total_amount);
	      	   }

	      	   if($res)
	      	   {
				   echo "success";
	      	   }else{
	      	   	   echo "fail";
	      	   }
		    }

	      	/*
	      		交易成功,不支持退款
	      	 */
		    if($trade_status == 'TRADE_FINISHED') 
		    {	
		    	$log['keyword'].='支付成功';

				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				//请务必判断请求时的total_amount与通知时获取的total_fee为一致的
				//如果有做过处理，不执行商户的业务程序
						
				//注意：
				//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
				
				echo "success";
		    }

	      	$res_count=M('log_notify_alipay')->where("order_stages_id='$out_trade_no' ")->count();

	      	if (!$res_count) 
	      	{
	      		M('log_notify_alipay')->add($log);
	      	}
      }


      /**
       * 支付同步地址
       */
      public function alipay_return()
      {
	      	header("Content-type: text/html; charset=utf-8");

	      	$request=I();

	      	//商户订单号
	      	$order_stages_id = $request['out_trade_no'];

			//支付宝交易号
		    $trade_no =$request['trade_no'];

		    $total_amount =$request['total_amount'];

	      	$res=$this->aop->rsaCheckV1($request,$this->alipayrsaPublicKey,$request['sign_type']);

	      	if ($res) 
	      	{	
	      		$payQueryResult=$this->query($order_stages_id,$trade_no);

	      		//trade_status :WAIT_BUYER_PAY 等待支付  TRADE_SUCCESS 成功
	      		if($payQueryResult["trade_status"] == 'TRADE_SUCCESS')
	      		{
	      			$result=M("orders")->where("zm_order_no='$out_trade_no' and order_type=2")->getField('order_id');

	      			if($result)
		      		{
		      			header("location:https://n.lvyuecp.com/waphb/paySuccess.html?money=$total_amount&order_id=$result");
		      		}else{
		      			
		      			$res=save_order_stages($order_stages_id,$total_amount);
			      		$order_id=M('order_stages')->where("id='$order_stages_id' ")->getField('order_id');
		            	header("location:https://n.lvyuecp.com/waphb/paySuccess.html?money=$total_amount&order_id=$order_id");
		      		}
	      		}else{
	      			header("location:https://n.lvyuecp.com/waphb/paySuccess.html?money=0.00");
	      		}
	      	}else{
	      		file_put_contents(time().'.txt',"同步支付验证失败");
	      	}
      }

}